<template>
  <Back title=" 更换头像" />

  <div class="change-avatar-page">
    <!-- 页面标题 -->
    <van-nav-bar title="更换头像" left-arrow @click-left="$router.back()" />
    <!-- 头像展示区域 -->
    <div class="avatar-container">
      <van-image :src="avatarUrl" width="150px" height="150px" round fit="cover" />
    </div>
    <!-- 上传按钮 -->
    <div class="upload-button-container">
      <van-button type="primary" @click="openFileInput">选择图片</van-button>
      <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" />
    </div>
    <!-- 保存按钮 -->
    <div class="save-button-container">
      <van-button type="success" @click="saveAvatar">保存</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { NavBar as VanNavBar, Image as VanImage, Button as VanButton } from 'vant';
import { useRouter } from 'vue-router';
import Back from '../utils/Back.vue';
// 头像链接
const avatarUrl = ref('https://via.placeholder.com/150');
// 文件输入框引用
const fileInput = ref(null);
// 当前选择的文件
const selectedFile = ref(null);
// 分片大小，这里设置为 1MB
const chunkSize = 1024 * 1024; 

// 打开文件选择框
const openFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (file) {
    selectedFile.value = file;
    const reader = new FileReader();
    reader.onload = (event) => {
      avatarUrl.value = event.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const router = useRouter();

// 获取本地存储的token
const getAuthHeader = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    alert('请先登录');
    router.push('/login');
    return null;
  }
  return {
    'Authorization': token
  };
};

// 保存头像
const saveAvatar = async () => {
  const headers = getAuthHeader();
  if (!headers) return;
  if (!selectedFile.value) {
    alert('请先选择图片');
    return;
  }

  const file = selectedFile.value;
  const totalChunks = Math.ceil(file.size / chunkSize);

  for (let i = 0; i < totalChunks; i++) {
    const start = i * chunkSize;
    const end = Math.min(start + chunkSize, file.size);
    const chunk = file.slice(start, end);

    const formData = new FormData();
    formData.append('chunk', chunk);
    formData.append('filename', file.name);
    formData.append('chunkIndex', i);
    formData.append('totalChunks', totalChunks);

    try {
      // 这里需要替换为你的后端上传接口地址
      const response = await fetch('http://127.0.0.1:8000/user/avatar/upload/', {
        method: 'POST',
        headers: headers,
        body: formData
      });

      if (response.status === 403) {
        handleAuthError();
        return;
      }
      if (!response.ok) {
        throw new Error('上传分片失败');
      }
    } catch (error) {
      console.error('上传分片时出错:', error);
      alert('上传失败，请重试');
      return;
    }
  }

  // 所有分片上传完成，通知后端合并文件
  try {
    const formData = new FormData();
    formData.append('filename', file.name);
    formData.append('totalChunks', totalChunks);
    // 这里需要替换为你的后端合并文件接口地址
    const response = await fetch('http://127.0.0.1:8000/user/avatar/merge/', {
      method: 'POST',
      headers: headers,
      body: formData
    });

    if (response.status === 403) {
      handleAuthError();
      return;
    }
    if (response.ok) {
      console.log('头像已保存');
      alert('头像已保存');
    } else {
      throw new Error('合并文件失败');
    }
  } catch (error) {
    console.error('合并文件时出错:', error);
    alert('上传失败，请重试');
  }
};

// 统一处理认证错误
const handleAuthError = () => {
  localStorage.removeItem('token');
  alert('登录已过期，请重新登录');
  router.push('/login');
};
</script>

<style scoped>
.change-avatar-page {
  padding: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.upload-button-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.save-button-container {
  display: flex;
  justify-content: center;
}
</style>